package clue_dao

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/user_db"
	"hft/Http/Services/new_clue/clue_model"
	"hft/Http/Services/new_clue/clue_utils"
	"hft/Http/Services/user/user_utils"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"hft/tools"
	"hft/tools/weixin/api"
	"time"

	"gorm.io/gorm"
)

// 查找客户
func FindUser(phone string, city int) (data *user_db.User, err error) {
	var user *user_db.User
	if err = global.OC_DB.Where("phone = ? AND city = ?", phone, city).First(&user).Error; err != nil {
		return nil, errors.New(e.UserNotFound)
	} else {
		return user, nil
	}
}

// 创建客户
func CreateUser(city int, ip string, activity clue_model.ActivityClue, port int) (err error) {
	var louRegionLink string
	var cityName string
	var regionName string
	// 找出楼盘
	var lou *admin.LouPan
	var region *admin.Region
	if activity.LouID != 0 {
		if err = global.OC_DB.First(&lou, activity.LouID).Error; err != nil { //找出楼盘ID
			return errors.New(e.LouPanNotExist)
		} else {
			louRegionLink = lou.RegionLink
			var cityTemp *admin.Region
			global.OC_DB.First(&cityTemp, city)
			cityName = cityTemp.Name
			regionName = user_utils.GetBelongName(lou.BelongName)
		}
		if err = global.OC_DB.Where("id = ?", lou.Region).First(&region).Error; err != nil {
			return errors.New(e.RegionNotFound)
		}
	} else {
		if err = global.OC_DB.First(&region, city).Error; err != nil {
			return errors.New(e.RegionNotFound)
		} else {
			louRegionLink = fmt.Sprintf("%v%v,", region.Link, region.ID)
			cityName = region.Name
			regionName = cityName
		}
	}
	var name string
	if activity.LouID == 0 {
		name = "公共组件"
	} else {
		name = lou.Name
	}
	// 生成UUID
	var clues []*user_db.Clue

	clues, err = GenerateActivityClue(clues, &activity, ip, port, regionName, name)
	if err != nil {
		return err
	}
	newPhone := tools.CorrectPhone(activity.Phone)
	release_time := FindCityTimeConfig(city)
	var uuid = tools.GenUUID2()
	var user = map[string]interface{}{
		"create_time":   time.Now(),
		"manager_id":    0,
		"uuid":          uuid,
		"phone":         newPhone,
		"city":          city,
		"city_link":     louRegionLink,
		"city_name":     cityName,
		"intend_lou":    name,
		"level":         "D",
		"intend_lou_id": uint(activity.LouID),
		"release_time":  release_time,
		"sex":           0,
		"delivery":      "",
		"lou_category":  "",
		"fitment":       "",
		"floor":         "",
		"aim":           "",
		"show":          0,
		"file":          0,
		"tag":           0,
	}
	if err = global.OC_DB.Model(&user_db.User{}).Create(&user).Error; err != nil {
		return errors.New(e.ErrorInfo)
	}
	var newUser *user_db.User
	global.OC_DB.Where("uuid = ?", uuid).First(&newUser)
	global.OC_DB.Model(&newUser).Association("Clues").Append(clues)
	// 添加区域
	global.OC_DB.Model(&user_db.UserRegion{}).Create(map[string]interface{}{
		"user_id":     newUser.ID,
		"region_id":   region.ID,
		"region_link": fmt.Sprintf("%v%v,", region.Link, region.ID),
	})
	return nil
}

// 判断是否在两个时间之间
func isBetween(value, a, b time.Time) bool {
	return value.After(a) && value.Before(b)
}

// 找出当前城市的时间的配置
func FindCityTimeConfig(city int) time.Time {
	// 找出当前的安全时间，确定客户的释放时间
	var citySet *admin.CitySetting
	global.OC_DB.Where("region = ?", city).First(&citySet)
	var startTime = citySet.FreeStartTime
	var endTime = citySet.FreeEndTime
	var s, e = clue_utils.ReturnTimeRange(startTime, endTime)
	var release_time time.Time
	if isBetween(time.Now(), s, e) {
		// 如果在保护期，那么过期时间就在保护期之后一小时
		release_time = e.Add(1 * time.Hour)
	} else {
		release_time = time.Now().Add(1 * time.Hour)
	}
	return release_time
}

// 找出该楼盘
func SendMessageToBroker(db *gorm.DB, phone string, lou_id uint, city int) error {
	var brokers []*admin.Account
	var name string
	var user *user_db.User
	err := db.Where("phone = ?", phone).Where("city = ?", city).First(&user).Error
	if err != nil {
		return errors.New(e.UserNotFound)
	}
	if lou_id != 0 {
		var lou *admin.LouPan
		err := db.First(&lou, lou_id).Error
		if err != nil {
			return errors.New(e.LouPanNotExist)
		}
		name = lou.Name
		if user.ManagerID == 0 {
			// 无人管理的客户
			db.
				Select("a.`status`,a.`id`,a.`open_id`,a.`phone`").
				Table("hft_account_lou_pan").
				Joins("LEFT JOIN hft_accounts as a on a.`id` = hft_account_lou_pan.`account_id`").
				Not("a.`status` = 0").
				Where("a.`open_id` IS NOT NULL").
				Not("a.`open_id` = ?", "").
				Unscoped().
				Group("a.`id`").
				Find(&brokers)
			// 找出经纪人
		} else {
			// 有人管理
			db.Find(&brokers, user.ManagerID)
			fmt.Println(22223, brokers)
		}
	} else {
		if user.ManagerID == 0 {
			var brokers []*admin.Account
			db.Where("belong = ?", city).Where("status = ?", 1).Find(&brokers)
		} else {
			// 有人管理
			db.Find(&brokers, user.ManagerID)
		}
		name = "公共组件"
	}
	user.Phone = utils.DesensitizePhoneNumber(user.Phone)
	// var wg sync.WaitGroup
	for _, v := range brokers {
		// wg.Add(1)
		go func(v *admin.Account) {
			api.WeiXinTemplate.SendClueMessage(v.OpenId, user, name)
		}(v)
	}
	// wg.Wait()
	return nil
}
